<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/4/17 16:50
 */


namespace App\Http\Controllers;


use App\Models\PermissionRole;
use App\Models\RoleUser;
use App\Permission;
use App\Role;
use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 管理员列表
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->isMethod('post')){
            $list = User::query()->where('id', '>',1)
                ->where('is_del',0)->with('roles')
                ->orderBy('id','desc')->paginate(15);
            foreach ($list as &$item){
                if ($item->roles && count($item->roles) > 0){
                    $item->role_name = $item->roles[0]->display_name;
                    $item->role_id = $item->roles[0]->id;
                }else{
                    $item->role_id = '';
                    $item->role_name = '--';
                }
            }
            return response()->json(['r' => 1000, 'i' => $list]);
        }
        return view('user.index');
    }

    /**
     * 角色列表
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function role(Request $request)
    {
        if ($request->isMethod('post')){
            if ($request->has('page')) {
                $list = Role::query()->orderBy('id','desc')->paginate(15);
            }else{
                $list = Role::query()->select('id as key','display_name as label')
                    ->orderBy('id','desc')->get();
            }
            return response()->json(['r' => 1000, 'i' => $list]);
        }
        return view('user.role');
    }

    /**
     * 权限列表
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function permission(Request $request)
    {
        if ($request->isMethod('post')){
            $userPermission = [];
            if ($request->has('page')) {
                $list = Permission::query()->paginate(15);
            }else{
                $role_id = intval($request->input('role_id'));
                $userPermission = PermissionRole::query()->where('role_id',$role_id)->pluck('permission_id');
                $list = Permission::query()->select('id as key','display_name as label')
                    ->orderBy('id','desc')->get();
            }
            return response()->json(['r' => 1000, 'i' => $list,'up' => $userPermission]);
        }
        return view('user.permission');
    }

    public function noPermission()
    {
        return view('user.noPermission');
    }

    /**
     * 添加/修改角色
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function submitRole(Request $request)
    {
        $this->validate($request,[
            'form.name' => 'required',
            'form.display_name' => 'required'
        ]);
        $form = $request->input('form');
        if ($form['id']){
            $action = '修改';
            $obj= Role::query()->findOrNew($form['id']);
        }else{
            $action = '添加';
            $obj = new Role();
            if (Role::query()->where('name',$form['name'])->exists()){
                throw new \Exception('角色名称重复了',2102);
            }
        }
        $obj->name = $form['name'];
        $obj->display_name = $form['display_name'];
        $obj->description = $form['description'];
        $obj->save();
        return response()->json(['r' => 1000, 'i' => '角色'.$action.'成功']);
    }

    /**
     * 添加/修改权限
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function submitPermission(Request $request)
    {
        $this->validate($request,[
            'form.name' => 'required',
            'form.display_name' => 'required'
        ]);
        $form = $request->input('form');
        if ($form['id']){
            $action = '修改';
            $obj= Permission::query()->findOrNew($form['id']);
        }else{
            $action = '添加';
            $obj = new Permission();
            if (Permission::query()->where('name',$form['name'])->exists()){
                throw new \Exception('权限名称重复了',2102);
            }
        }
        $obj->name = $form['name'];
        $obj->display_name = $form['display_name'];
        $obj->description = $form['description'];
        $obj->save();
        return response()->json(['r' => 1000, 'i' => '权限'.$action.'成功']);
    }

    /**
     * 分配权限
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function allotPermission(Request $request)
    {
        $role_id = intval($request->input('role_id'));
        $permission_id = $request->input('permission_id');
        $pid_arr = $permission_id ? explode(',',$permission_id) : [];
        \DB::beginTransaction();
        try {
            PermissionRole::query()->where('role_id', $role_id)->delete();
            $data = array();
            foreach ($pid_arr as $pid) {
                $data[] = array(
                    'role_id'       => $role_id,
                    'permission_id' => $pid
                );
            }
            \Log::info('data',$data);
            PermissionRole::query()->insert($data);
            \DB::commit();
            return response()->json(['r' => 1000,'status' => 'success','i' => '权限分配成功']);
        }catch (\Throwable $e){
            \DB::rollBack();
            return response()->json(['r' => 2101,'status' => 'error','i' => '分配失败,'.$e->getMessage()]);
        }
    }

    /**
     * 删除角色
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delRole(Request $request)
    {
        $role_id = intval($request->input('role_id'));
        \DB::beginTransaction();
        try{
            Role::query()->where('id',$role_id)->delete();
            PermissionRole::query()->where('role_id',$role_id)->delete();
            RoleUser::query()->where('role_id',$role_id)->delete();
            \DB::commit();
            return response()->json(['r' => 1000,'status' => 'success','i' => '角色删除成功']);
        }catch (\Throwable $e){
            \DB::rollBack();
            return response()->json(['r' => 1000,'status' => 'error','i' => '角色删除失败,'.$e->getMessage()]);
        }
    }

    /**
     * 删除权限
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delPermission(Request $request)
    {
        $permission_id = intval($request->input('permission_id'));
        \DB::beginTransaction();
        try{
            Permission::query()->where('id',$permission_id)->delete();
            PermissionRole::query()->where('permission_id',$permission_id)->delete();
            \DB::commit();
            return response()->json(['r' => 1000,'status' => 'success','i' => '权限删除成功']);
        }catch (\Throwable $e){
            \DB::rollBack();
            return response()->json(['r' => 1000,'status' => 'error','i' => '权限删除失败,'.$e->getMessage()]);
        }
    }

    /**
     * 添加用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function addUser(Request $request)
    {
        $form = $request->input('form');
        if (User::query()->where('name',$form['name'])->exists()){
            throw new \Exception('用户名已经存在',2103);
        }
        $obj = new User();
        $obj->name = $form['name'];
        $obj->email = $form['email'];
        $obj->password = bcrypt($form['password']);
        if ($obj->save()){
            $roleObj = new RoleUser();
            $roleObj->user_id = $obj->id;
            $roleObj->role_id = $form['role_id'];
            $roleObj->save();
            return response()->json(['r' => 1000,'status' => 'success','i' => '用户添加成功']);
        }else{
            return response()->json(['r' => 2000,'status' => 'error','i' => '用户添加失败']);
        }
    }

    /**
     * 编辑用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function editUser(Request $request)
    {
        $form = $request->input('form');
        if (User::query()->where('name',$form['name'])->where('id','<>',$form['id'])->exists()){
            throw new \Exception('用户名已经存在',2103);
        }
        $obj = User::query()->findOrFail($form['id']);
        $obj->name = $form['name'];
        $obj->email = $form['email'];
        $obj->is_disable = $form['is_disable'];
        if (isset($form['password'])){
            if (strlen($form['password']) < 6){
                throw new \Exception('密码不能少于6位数',2103);
            }
            $obj->password = bcrypt($form['password']);
        }
        if ($obj->save()){
            $role = RoleUser::firstOrNew(['user_id' => $form['id']]);
            $role->role_id = $form['role_id'];
            $role->save();
            return response()->json(['r' => 1000,'status' => 'success','i' => '用户编辑成功']);
        }else{
            return response()->json(['r' => 2000,'status' => 'error','i' => '用户编辑失败']);
        }
    }

    /**
     * 删除用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUser(Request $request)
    {
        $id = $request->input('id');
        if ($id == $request->user()->id){
            throw new \Exception('不能删除当前登录账号',2101);
        }
        $user = User::query()->findOrFail($id);
        $user->is_del = 1;
        $user->save();
        return response()->json(['r' => 1000,'status' => 'success','i' => '用户删除成功']);
    }
}